import {addUserGps} from '@/api/configure.js';
import {getLocation, getSystemInfo, getUserInfo, timesFormat} from '@/util/util.js';
import {ClockIn} from '@/util/ClockIn.js';
export class UploadGps {
	constructor() {
		this.userGpsList = [];
		this.timer = null;
		this.clockIn = new ClockIn();
	}

	async getLocation() {
		let sys = await getSystemInfo();
		let loc = await getLocation({}, 'uni');
		let userInfo = getUserInfo();

		let createTime = new Date().getTime();

		let userGps = {
			createTime: timesFormat(createTime),
			gpsStatus: (loc.latitude) ? 'GPS在状态正常' : 'GPS在状态异常',
			lat: loc.latitude,
			lng: loc.longitude,
			manufacturer: sys.brand,
			model: sys.model,
			satellites: '36',
			userId: userInfo['userId'],
			uuid: sys.deviceId,
			version: sys.version
		}
		
		this.userGpsList.push(userGps);
	}

	async uploadLocation() {
		let params = {};

		params.userGpsList = JSON.stringify(this.userGpsList);

		let res = await addUserGps(params);
	}

	async cycle() {
		if(this.timer) {
			clearTimeout(this.timer);
		}

		await this.getLocation();

		if(this.userGpsList.length >= 8){
			await this.uploadLocation();

			this.userGpsList = [];
		}
		
		this.timer = setTimeout(this.cycle.bind(this), 15000);
	}

	async pause() {
		if(this.timer) {
			clearTimeout(this.timer);
			this.timer = null;
		}
	}
	
	async check() {
		return await new Promise( async(resolve, reject) => {
			let userInfo = getUserInfo();
			
			let clockInData = await this.clockIn.getData();
			
			let today = timesFormat(new Date().getTime(), 'yyyyMMdd');
			
			if(userInfo && clockInData && clockInData.date == today && clockInData.payload.checkIn && clockInData.payload.checkIn == 1){
				resolve();
			} else {
				reject();
			}
		})
	}
}
